package org.dylan.bdf.system.controller;

import org.apache.shiro.authz.annotation.RequiresUser;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.dylan.bdf.system.model.LogLevel;
import org.dylan.bdf.system.model.LogType;
import org.dylan.bdf.system.service.LogService;
import org.dylan.security.entity.IUser;
import org.dylan.security.util.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class LoginController {
	@Autowired
	private LogService logService;

	/**
	 * 登录
	 */
	@RequestMapping(value = "login", method = RequestMethod.GET)
	public String login() {
		IUser user = SecurityUtils.getUser();
		if (user != null && user.getId() == null) {// 已经登录
			return "redirect:/";
		}
		return "login";
	}

	/**
	 * 登录失败，真正登录的POST请求由Filter完成
	 */
	@RequestMapping(value = "login", method = RequestMethod.POST)
	public String login(
			@RequestParam(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM) String userName,
			Model model) {
		model.addAttribute(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM,
				userName);
		return "login";
	}

	/**
	 * 登录成功，进入管理首页
	 */
	@RequiresUser
	@RequestMapping(value = "/")
	public String index() {
		IUser user = SecurityUtils.getUser();
		if (user == null || user.getId() == null) {
			return "redirect:/login";
		}
		// 进入系统,
		// TODO 记录用户登录的日志，暂时记在这里，由于进入首页时，并不一定是初次登录系统，所以这里的新增日志需要移到其他地方
		logService.addLog(LogLevel.info, LogType.type(LogType.Type.login.name()), "用户"+user.getUsername()+"登录系统.");
		return "index";
	}

	public LogService getLogService() {
		return logService;
	}

	public void setLogService(LogService logService) {
		this.logService = logService;
	}

}
